package com.yixq.soa.service.web.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.mvc.condition.RequestCondition;



public class ApiVesrsionCondition implements RequestCondition<ApiVesrsionCondition> {
    private static Logger log = LoggerFactory.getLogger(ApiVesrsionCondition.class); 
    
	// 路径中版本的前缀， 这里的形式
    private final static Pattern VERSION_PREFIX_PATTERN = Pattern.compile("/v([0-9.]+)/?");// // v([0-9.abcd]+)[/\\?;]  v([0-9.abcd]+)[/\\?;]?.*$
	
	private String version = "v1";
	
	public ApiVesrsionCondition(String version){
        this.version = version;
    }
	
	public String getApiVersion() {
        return version;
    }
	
	@Override
	public ApiVesrsionCondition combine(ApiVesrsionCondition other) {
		// 采用最后定义优先原则，则方法上的定义覆盖类上面的定义
        return new ApiVesrsionCondition(other.getApiVersion());
	}

	@Override
	public ApiVesrsionCondition getMatchingCondition(HttpServletRequest request) {
		String pathinfo = request.getPathInfo();
		
		if(pathinfo == null){
			pathinfo = request.getRequestURI();
		}

//		String host = request.getServletPath();
//		String s2 = request.getRequestURI();
//		StringBuffer ss = request.getRequestURL();
//		Object o1 = request.getCookies();
//		Object o2 = request.getContextPath();
		
		if(pathinfo == null){
			return null;
		}
		Matcher m = VERSION_PREFIX_PATTERN.matcher(pathinfo);
        if(m.find()){
        	String version = String.valueOf(m.group(1));
        	request.setAttribute("ver", version);
        	
        	int r = VersionUtils.compareVersion(version , this.version);
			if(r >= 0) // 如果请求的版本号大于配置版本号， 则满足
			//if(this.version != null && this.version.equals(version)) //严格相等才满足
			{
				
				log.debug("ApiVersion select["+this.version+"] for "+pathinfo);
				return this;
			}else{
				log.info("!!!!!ApiVersion can't match! ver="+version+",url="+pathinfo);
			}
        }
		return null;
	}

	@Override
	public int compareTo(ApiVesrsionCondition other, HttpServletRequest request) {

		return VersionUtils.compareVersion(other.getApiVersion(),version);
	}
	
}
